package server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;

public class TaskProtocol
{
    Socket socket;

    public TaskProtocol(Socket socket)
        throws IOException
    {
        this.socket = socket;
    }

    public void writeString(String str)
        throws IOException
    {
        DataOutputStream socketOut = new DataOutputStream(socket.getOutputStream());
        byte [] strByteData = str.getBytes();
        socketOut.writeInt(strByteData.length);
        socketOut.write(strByteData);
    }

    public String readString()
            throws IOException
    {
        String resultString = null;
        DataInputStream socketInput = new DataInputStream(socket.getInputStream());

        try
        {
            int bufSize = socketInput.readInt();
            byte [] buffer = new byte[bufSize];
            int readBytesCount = socketInput.read(buffer);
            if (readBytesCount != -1)
            {
                resultString = new String(buffer);
            }
        }
        catch (EOFException eofException)
        {
            //do nothing
        }
        return resultString;
    }

}
